﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Linq;
using Windows.ApplicationModel;
using Windows.Storage;
using com.IronOne.BoardPACWinAppBO.Settings;

namespace com.IronOne.BoardPACWinApp.Helpers
{
    public class AppSettingsManager : IAppSettingsManager
    {
        public bool WriteAppSettingsToLocalSettings(AppSettingModel model)
        {
            //Write to local settings
            try
            {
                //ApplicationData.Current.LocalSettings.Values["AppVersion"] = model.AppVersion;
                ApplicationData.Current.LocalSettings.Values["ServerUrl"] = model.ServerUrl;
                ApplicationData.Current.LocalSettings.Values["DateFormats"] = model.DateFormats;
                ApplicationData.Current.LocalSettings.Values["DateFormatSelected"] = model.DateFormatSelected;
                ApplicationData.Current.LocalSettings.Values["SyncFrequencies"] = model.SyncFrequencies;
                ApplicationData.Current.LocalSettings.Values["SyncFrequency"] = model.SyncFrequencySelected;
                //ApplicationData.Current.LocalSettings.Values["SyncSettings"] = model.SyncSettings;
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public bool WriteAppSettingsToRoamingSettings(AppSettingModel model)
        {
            try
            {
                //ApplicationData.Current.RoamingSettings.Values["AppVersion"] = model.AppVersion;
                ApplicationData.Current.RoamingSettings.Values["ServerUrl"] = model.ServerUrl;
                ApplicationData.Current.RoamingSettings.Values["DateFormats"] = model.DateFormats;
                ApplicationData.Current.RoamingSettings.Values["DateFormatSelected"] = model.DateFormatSelected;
                ApplicationData.Current.RoamingSettings.Values["SyncFrequencies"] = model.SyncFrequencies;
                ApplicationData.Current.RoamingSettings.Values["SyncFrequency"] = model.SyncFrequencySelected;
                //ApplicationData.Current.RoamingSettings.Values["SyncSettings"] = model.SyncSettings;
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public AppSettingModel ReadAppSettingsFromLocalSettings()
        {
            try
            {
                var asm = new AppSettingModel
                {
                    ServerUrl = ApplicationData.Current.LocalSettings.Values["ServerUrl"].ToString(),
                    DateFormats = (List<CustomKeyValuePair<string, string>>)
                        ApplicationData.Current.LocalSettings.Values["DateFormats"],
                    DateFormatSelected = (CustomKeyValuePair<string, string>)
                        ApplicationData.Current.LocalSettings.Values["DateFormatSelected"],
                    SyncFrequencies = (List<CustomKeyValuePair<string, string>>)
                        ApplicationData.Current.LocalSettings.Values["SyncFrequencies"],
                    SyncFrequencySelected =
                        (CustomKeyValuePair<string, string>)
                            ApplicationData.Current.LocalSettings.Values["SyncFrequency"]
                };
                //asm.AppVersion = ApplicationData.Current.LocalSettings.Values["AppVersion"].ToString();
                //asm.SyncSettings = Convert.ToBoolean(ApplicationData.Current.LocalSettings.Values["SyncSettings"]);
                return asm;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public AppSettingModel ReadAppSettingsFromRoamingSettings()
        {
            try
            {
                var asm = new AppSettingModel
                {
                    ServerUrl = ApplicationData.Current.RoamingSettings.Values["ServerUrl"].ToString(),
                    DateFormats = (List<CustomKeyValuePair<string, string>>)
                        ApplicationData.Current.RoamingSettings.Values["DateFormats"],
                    DateFormatSelected = (CustomKeyValuePair<string, string>)
                        ApplicationData.Current.RoamingSettings.Values["DateFormatSelected"],
                    SyncFrequencies = (List<CustomKeyValuePair<string, string>>)
                        ApplicationData.Current.RoamingSettings.Values["SyncFrequencies"],
                    SyncFrequencySelected =
                        (CustomKeyValuePair<string, string>)
                            ApplicationData.Current.RoamingSettings.Values["SyncFrequency"]
                };
                //asm.AppVersion = ApplicationData.Current.RoamingSettings.Values["AppVersion"].ToString();
                //asm.SyncSettings = Convert.ToBoolean(ApplicationData.Current.RoamingSettings.Values["SyncSettings"]);
                return asm;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public async Task<AppSettingModel> ReadAppSettingsFromXmlFile()
        {
            try
            {
                var asm = new AppSettingModel();

                var appSettingsPath = Path.Combine(Package.Current.InstalledLocation.Path, @"AppSettings.xml");
                var file = await StorageFile.GetFileFromPathAsync(appSettingsPath);
                var xmlText = await FileIO.ReadTextAsync(file);

                var settingDataDoc = XDocument.Parse(xmlText.Trim());
                var appSettingsElemt = settingDataDoc.Element("Settings").Element("AppSettings");

                var ver = Package.Current.Id.Version;
                asm.AppVersion = ver.Major + "." + ver.Minor + "." + ver.Build;
                    //appSettingsElemt.Element("AppVersion").Value.Trim();

                asm.MinWebVersion = appSettingsElemt.Element("MinWebVersion").Value.Trim();

                asm.ServerUrl = appSettingsElemt.Element("ServerUrl").Value.Trim();
                asm.SyncSettings = Convert.ToBoolean(appSettingsElemt.Element("SyncSettings").Value.Trim());

                var dtFormatsTemp =
                    appSettingsElemt.Element("DateFormats")
                        .Descendants("Format")
                        .ToDictionary(item => item.Value, item => item.Attribute("Eg").Value);
                asm.DateFormats =
                    dtFormatsTemp.Select(
                        kvp => new CustomKeyValuePair<string, string> {Key = kvp.Key, Value = kvp.Value}).ToList();
                asm.DateFormatSelected =
                    asm.DateFormats.Find(x => x.Key.Equals(appSettingsElemt.Element("DateFormatSelected").Value.Trim()));

                var sycFreqsTemp =
                    appSettingsElemt.Element("SyncFrequencies")
                        .Descendants("FreqVal")
                        .ToDictionary(item => item.Value, item => item.Attribute("Eg").Value);
                asm.SyncFrequencies =
                    sycFreqsTemp.Select(kvp => new CustomKeyValuePair<string, string> {Key = kvp.Key, Value = kvp.Value})
                        .ToList();
                asm.SyncFrequencySelected =
                    asm.SyncFrequencies.Find(
                        x => x.Key.Equals(appSettingsElemt.Element("SyncFrequencySelected").Value.Trim()));

                return asm;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public async Task<AppSettingModel> ReadDateFormatsNSyncFreqsFromXmlFile()
        {
            try
            {
                var asm = new AppSettingModel();

                var appSettingsPath = Path.Combine(Package.Current.InstalledLocation.Path, @"AppSettings.xml");
                var file = await StorageFile.GetFileFromPathAsync(appSettingsPath);
                var xmlText = await FileIO.ReadTextAsync(file);

                var settingDataDoc = XDocument.Parse(xmlText.Trim());
                var appSettingsElemt = settingDataDoc.Element("Settings").Element("AppSettings");

                asm.MinWebVersion = appSettingsElemt.Element("MinWebVersion").Value;

                var dtFormatsTemp =
                    appSettingsElemt.Element("DateFormats")
                        .Descendants("Format")
                        .ToDictionary(item => item.Value, item => item.Attribute("Eg").Value);
                asm.DateFormats =
                    dtFormatsTemp.Select(
                        kvp => new CustomKeyValuePair<string, string> {Key = kvp.Key, Value = kvp.Value}).ToList();

                var sycFreqsTemp =
                    appSettingsElemt.Element("SyncFrequencies")
                        .Descendants("FreqVal")
                        .ToDictionary(item => item.Value, item => item.Attribute("Eg").Value);
                asm.SyncFrequencies =
                    sycFreqsTemp.Select(kvp => new CustomKeyValuePair<string, string> {Key = kvp.Key, Value = kvp.Value})
                        .ToList();

                return asm;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public async Task<List<CustomKeyValuePair<string, string>>> ReadDateFormatsFromXmlFile()
        {
            try
            {
                var appSettingsPath = Path.Combine(Package.Current.InstalledLocation.Path, @"AppSettings.xml");
                var file = await StorageFile.GetFileFromPathAsync(appSettingsPath);
                var xmlText = await FileIO.ReadTextAsync(file);

                var settingDataDoc = XDocument.Parse(xmlText.Trim());
                var appSettingsElemt = settingDataDoc.Element("Settings").Element("AppSettings");

                var dtFormatsTemp =
                    appSettingsElemt.Element("DateFormats")
                        .Descendants("Format")
                        .ToDictionary(item => item.Value, item => item.Attribute("Eg").Value);
                return
                    dtFormatsTemp.Select(
                        kvp => new CustomKeyValuePair<string, string> {Key = kvp.Key, Value = kvp.Value}).ToList();
            }
            catch (Exception)
            {
                return null;
            }
        }

        public async Task<List<CustomKeyValuePair<string, string>>> ReadSyncFrequenciesFromXmlFile()
        {
            try
            {
                var appSettingsPath = Path.Combine(Package.Current.InstalledLocation.Path, @"AppSettings.xml");
                var file = await StorageFile.GetFileFromPathAsync(appSettingsPath);
                var xmlText = await FileIO.ReadTextAsync(file);

                var settingDataDoc = XDocument.Parse(xmlText.Trim());
                var appSettingsElemt = settingDataDoc.Element("Settings").Element("AppSettings");

                var sycFreqsTemp =
                    appSettingsElemt.Element("SyncFrequencies")
                        .Descendants("FreqVal")
                        .ToDictionary(item => item.Value, item => item.Attribute("Eg").Value);
                return
                    sycFreqsTemp.Select(kvp => new CustomKeyValuePair<string, string> {Key = kvp.Key, Value = kvp.Value})
                        .ToList();
            }
            catch (Exception)
            {
                return null;
            }
        }

        /*public async Task<LogOnModel> ReadSupportInfoFromXmlFile()
        {
            try
            {
                string appSettingsPath = Path.Combine(Windows.ApplicationModel.Package.Current.InstalledLocation.Path, @"AppSettings.xml");
                StorageFile file = await StorageFile.GetFileFromPathAsync(appSettingsPath);
                string xmlText = await FileIO.ReadTextAsync(file);

                XDocument settingDataDoc = XDocument.Parse(xmlText.Trim());
                XElement suppInfoElemt = settingDataDoc.Element("Settings").Element("SupportInfo");

                LogOnModel model = new LogOnModel();

                model.SupportContactName = suppInfoElemt.Element("ContactName").Value;                
                model.SupportContactDesig = suppInfoElemt.Element("ContactDesignation").Value;
                model.SupportContactTelephone = suppInfoElemt.Element("SupportTelephone").Value.Trim();
                model.SupportContactEmail = suppInfoElemt.Element("SupportEmail").Value.Trim();

                return model;
            }
            catch (Exception)
            {
                return null;
            }
        }*/

        /// <summary>
        ///     If IsPinned == true returns true
        /// </summary>
        /// <returns></returns>
        public bool GetAppBarPinnedStatus()
        {
            if (ApplicationData.Current.LocalSettings.Values["IsPinned"] == null)
            {
                return false;
            }
            return Convert.ToBoolean(ApplicationData.Current.LocalSettings.Values["IsPinned"]);
        }

        public void SetAppBarPinnedStatus(bool val)
        {
            ApplicationData.Current.LocalSettings.Values["IsPinned"] = val;
        }
    }
}